package com.whfc.common.helmet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.whfc.common.util.DateUtil;
import com.whfc.common.util.HttpUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author likang
 * @description 智慧安全帽api
 * @date 2020-09-04
 */
public class SafetyHelmetApi {

    private static final Logger logger = LoggerFactory.getLogger(SafetyHelmetApi.class);

    /**
     * 获取数据采集信息列表
     */
    private static final String GET_DEPT = "http://182.92.108.122:1080/cmt/otherDevice/deplist?action=api";

    /**
     * 获取数据采集信息列表
     */
    private static final String GET_PHOTOANDVIDEO_URL = "http://182.92.108.122:1080/smallApps/sichuanInfo/selectInfo_New";

    /**
     * 根据查询到的信息查询文件详情
     */
    private static final String GET_FILEID_URL = "http://182.92.108.122:1080/smallApps/sichuanInfo/selectFileByInfoId_Old";

    /**
     * 获取视频播放地址
     */
    private static final String GET_VIDEO_URL = "http://182.92.108.122:1080/cmt/user/daq/view/video";

    /**
     * 获取GPS位置
     */
    private static final String GET_GPSLOCATION = "http://182.92.108.122:1080/api/userapi/gps?action=api";

    /**
     * 获取在线状态
     */
    private static final String GET_ONLINE_STATE = "http://182.92.108.122:1080/cmt/user/sipstate?type=api";

    /**
     * 账号
     */
    public static final String USERNAME = "9940000";

    /**
     * 获取组织机构
     */
    public static List<HelmetDeptListDTO> getDeptInfo(String sipNumber, String sipPassword) {
        try {
            String url = GET_DEPT + "&sipNumber=" + sipNumber + "&sipPassword=" + sipPassword;
            logger.debug("获取组织机构请求地址，请求地址，url:{}", url);
            String response = HttpUtil.doGet(url);
            logger.debug("获取组织机构,返回结果，response：{}", response);
            if (!"[]".equals(response)) {
                List<HelmetDeptListDTO> deptListDTOS = JSONArray.parseArray(response, HelmetDeptListDTO.class);
                return deptListDTOS;
            }
        } catch (Exception ex) {
            logger.warn("", ex);
        }

        return Collections.emptyList();
    }

    /**
     * 获取安全帽GPS位置信息
     */
    public static List<HelmetGPSDTO> getHelmetGPS(List<String> sipNumberList) {

        try {
            if (sipNumberList != null && sipNumberList.size() > 0) {
                String sips = StringUtils.join(sipNumberList, ",");
                String url = GET_GPSLOCATION + "&sipnum=" + sips;
                logger.debug("获取安全帽GPS位置信息请求地址，：url：{}", url);
                String response = HttpUtil.doGet(url);
                logger.debug("获取到安全帽GPS位置信息,返回结果，response：{}", response);
                if (!"[]".equals(response)) {
                    List<HelmetGPSDTO> gpsList = JSONArray.parseArray(response, HelmetGPSDTO.class);
                    logger.debug("获取到安全帽GPS位置信息,返回结果，gps：{}", gpsList.toString());
                    return gpsList;
                }
            }
        } catch (Exception ex) {
            logger.warn("", ex);
        }
        return Collections.emptyList();
    }

    /**
     * 获取安全帽拍录视频文件详情列表
     */
    public static List<VideoFileDetailDTO> getVideoFileList(PhotoAndVideoListQO listQO) {

        try {
            List<VideoFileDetailDTO> result = new ArrayList<>();

            //封装请求体参数
            Map<String, String> bodys = new HashMap<>();
            bodys.put("userName", listQO.getUserName());
            //取出sip数组的拼接字符串
            if (listQO.getSips() != null && listQO.getSips().size() > 0) {
                String sipJoin = StringUtils.join(listQO.getSips(), ",");
                bodys.put("sips", sipJoin);
            }
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (listQO.getStartTime() != null) {
                bodys.put("startTime", format.format(listQO.getStartTime()));
            }
            if (listQO.getEndTime() != null) {
                bodys.put("endTime", format.format(listQO.getEndTime()));
            }
            if (listQO.getPageNum() != null) {
                bodys.put("pageNum", String.valueOf(listQO.getPageNum()));
            }
            if (listQO.getPageSize() != null) {
                bodys.put("pageSize", String.valueOf(listQO.getPageSize()));
            }
            logger.info("获取安全帽照片/视频数据采集列表,请求报文，bodys:{}", bodys);
            //查询获取安全帽数据列表
            String response = HttpUtil.doPost(GET_PHOTOANDVIDEO_URL, bodys);
            logger.info("获取安全帽照片/视频数据采集列表,返回结果，response：{}", response);
            JSONObject retJSON = JSON.parseObject(response);
            if (retJSON != null && "true".equals(retJSON.getString("success"))) {
                JSONObject data = retJSON.getJSONObject("data");
                PhotoAndVideoListDTO photoAndVideoListDTO = data.toJavaObject(PhotoAndVideoListDTO.class);
                List<PhotoAndVideoDTO> list = photoAndVideoListDTO.getList();
                if (list != null && list.size() > 0) {
                    for (PhotoAndVideoDTO photoAndVideoDTO : list) {

                        //过滤只需要取出视频文件
                        if (photoAndVideoDTO.getDesInfo().equals("拍录视频")) {
                            Integer dataId = photoAndVideoDTO.getDataId();
                            String url = GET_FILEID_URL + "?infoId=" + dataId;
                            logger.info("拼接获取安全帽拍录视频的文件详情地址，请求地址，url：{}", url);
                            String responseFile = HttpUtil.doGet(url);
                            logger.info("获取安全帽拍录视频数据文件详情,返回结果， responseFile：{}", responseFile);
                            JSONObject retJSONFile = JSON.parseObject(responseFile);

                            //处理获取的视频文件详情结果
                            if (retJSONFile != null && "true".equals(retJSONFile.getString("success"))) {
                                JSONArray dataFile = retJSONFile.getJSONArray("data");
                                if (dataFile != null && dataFile.size() > 0) {
                                    VideoFileDetailDTO videoFileDetail = dataFile.getJSONObject(0).toJavaObject(VideoFileDetailDTO.class);
                                    //获取视频文件的播放地址，补全文件详情中的播放地址
                                    String videoUrl = GET_VIDEO_URL + "?fileId=" + videoFileDetail.getId();
                                    logger.info("获取拍录视频数据的播放地址,播放地址，videoUrl：{}", videoUrl);
                                    videoFileDetail.setFileUrl(videoUrl);
                                    result.add(videoFileDetail);
                                }
                            }
                        }
                    }

                }
            }
            //对结果进行判断
            if (result != null && result.size() > 0) {
                logger.info("获取了拍录视频文件列表信息，result：{}", result.toString());
                return result;
            }
        } catch (Exception ex) {
            logger.warn("", ex);
        }

        return Collections.emptyList();
    }

    /**
     * 获取安全帽在线状态
     * 0 离线 1 在线   2忙线
     */
    public static Integer isOnline(String sipAccount) {
        try {
            String url = GET_ONLINE_STATE + "&sipAccount=" + sipAccount;
            logger.info("获取安全帽在线状态，请求地址，url:{}", url);
            Map<String, String> map = new HashMap<>();
            //  map.put("sipAccount",null);
            String response = HttpUtil.doPost(url, map);
            logger.info("获取安全帽在线状态,返回结果，response：{}", response);
            String replace = response.replace("\"", "");
            Integer hotState;
            if (replace.equals("0")) {
                hotState = 1;
            } else {
                hotState = 0;
            }
            return hotState;
        } catch (Exception ex) {
            logger.warn("", ex);
        }
        return 0;
    }

    public static void main(String[] args) {
        PhotoAndVideoListQO photoAndVideoListQO = new PhotoAndVideoListQO();
        photoAndVideoListQO.setUserName("9940000");
        List<String> list = new ArrayList<>();
        list.add("9940001");
        list.add("9940002");
        list.add("9940003");
        list.add("9940004");
        photoAndVideoListQO.setSips(list);
        photoAndVideoListQO.setStartTime(DateUtil.addDays(new Date(), -10));
        photoAndVideoListQO.setEndTime(new Date());

        List<VideoFileDetailDTO> videoFileList = getVideoFileList(photoAndVideoListQO);
        System.out.println(videoFileList.toString());

        List<HelmetGPSDTO> helmetGPS = getHelmetGPS(list);
        System.out.println(helmetGPS.toString());

        System.out.println(isOnline("9940004"));
    }
}

